import { DesignContext, IDCtx } from "@/components/editor/context";
import { getAmisEnv, schemaUtil } from "@/components/editor/util";
import { Button, Input, Layout, cssVar, message, udp } from "@cscec/udp-ui";
import { Editor, ShortcutKey } from 'amis-editor';
import React, { useContext } from "react";
import { IStore } from "./type";
import { CloudUploadOutlined, CodepenCircleOutlined, EyeOutlined, SaveOutlined } from "@ant-design/icons";
import { saveOrUpdateModuleHomepage, saveOrUpdatePersonalModuleHomepage } from "./service";

function Header() {
    const { store, setStore } = useContext<IDCtx<IStore>>(DesignContext);

    const onPreview = () => {
        schemaUtil.setData({ ...store.value, amisPackages: store.packages });
        const appTitle = `${udp.getQueryValue('appTitle') || '门户装修'}-预览`;
        udp.open('/portal/preview', {
            outLink: !udp.isRunMaster, preview: 1, ...udp.getQueryValue(''), id: '', type: 'module', AppTitle: appTitle,
        });
    };

    // 0 是保存，1是发布
    const getHandle = (useFlg: number = 0) => async () => {
        if (!store.title) {
            message.warn('名称不能为空！');
            return;
        }
        let key;
        let clearPersonal;
        if (useFlg === 1 && udp.getQueryValue('type') !== 'personal') {
            if (await udp.confirm(`是否清除个人首页模块？`)) {
                clearPersonal = 1;
            }
        }
        const requestData = {
            id: store.id,
            moduleCode: udp.getQueryValue('moduleCode'),
            homepageName: store.title,
            homepageContent: udp.jsonString({ ...store.value, amisPackages: store.packages }),
            useFlg,
            clearPersonal,
        };
        if (udp.getQueryValue('type') === 'personal') {
            // 个人首页保存更新
            key = await saveOrUpdatePersonalModuleHomepage({
                ...requestData,
                homepageId: store.homepageId,
                homepageVersion: store.homepageVersion
            });
        } else {
            key = await saveOrUpdateModuleHomepage(requestData);
        }
        if (key) {
            const refreshKey = udp.getQueryValue('refreshKey');
            refreshKey && udp.refreshList(refreshKey, { id: key, type: useFlg ? 'publish' : 'save' });
            setStore({ id: key, useFlg });
        }

    };

    return (
        <div className="Editor-header">
            <div className="Editor-title">
                <CodepenCircleOutlined style={{ color: cssVar.primaryColor, marginRight: 4, fontSize: 18 }} />
                <Input style={{ margin: '0 24px 0 12px', width: 260 }} value={store.title} onChange={(title) => setStore({ title })} />
            </div>
            <div className="Editor-header-actions">
                <ShortcutKey />
                <Button
                    className="m-l"
                    icon={<EyeOutlined />}
                    onClick={onPreview}
                >
                    预览
                </Button>
                <Button
                    className="m-l"
                    onClick={getHandle(store.useFlg)}
                    icon={<SaveOutlined />}
                >
                    保存
                </Button>
                {<Button
                    type="primary"
                    className="m-l"
                    icon={<CloudUploadOutlined />}
                    onClick={getHandle(1)}
                >
                    发布
                </Button>}
            </div>
        </div>
    );
}

export function ModuleHome({ store, amisRef, onChange, plugins }) {
    return (
        <Layout className="Editor-Container" loading={store.loading}>
            <Header />
            <Layout.Flex className="Editor-inner">
                <Editor
                    key="editor"
                    ref={amisRef}
                    theme="antd"
                    value={store.value}
                    onChange={onChange}
                    isMobile={false}
                    className="is-fixed"
                    plugins={plugins}
                    showCustomRenderersPanel
                    amisEnv={getAmisEnv('design')}
                />
            </Layout.Flex>
        </Layout>

    );
}